<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-09-26
 * Time: 11:50
 */
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Request;

class IndexController  extends Controller
{
    /*首页*/
    public function  index(Request $request){
        $trd_session =$request->input('trd_session');
        $condition = [
            'is_cancel' => 0,
            'is_global' => 0,
            'status' => 0
        ];
        $prize = DB::table('prize')->where($condition)->get();
        if($trd_session){
            $member_id = DB::table('token')->where('token',$trd_session)->value('member_id');
        }
        $prize =$prize-> toArray();
        if ($prize) {
            foreach ($prize as & $value) {
                $value->imgurl = DB::table('resource')->where('id',$value->attach_id)->value('route');
                $value->joined =  DB::table('order')->where([['prize_id',$value->id],['member_id',$member_id]])->first()?DB::table('order')->where([['prize_id',$value->id],['member_id',$member_id]])->first() : false;
            }
        }
        $info=array('info'=>$prize,'status'=>1);
        return json_encode($info,JSON_UNESCAPED_UNICODE);

    }
    /*统计*/
    public function total()
    {
        $jiezhi = date("Y-m-d",strtotime("-1 day"));
        $total = DB::table('prize_result')->count();
        $total=$total?$total:0;
        $info = array('info'=>compact('jiezhi', 'total'),'status'=>1);
        return  json_encode($info);
    }

    /*个人信息*/
    public function my(Request $request)
    {
        $trd_session =$request->input('trd_session');
        $member_id = DB::table('token')->where('token',$trd_session)->value('member_id');
        $list = DB::table('member')->where('id',$member_id)->first();
        $info =array('info'=>$list,'status'=>1);
        return json_encode($info);
    }
    /*广告*/
    public function advertisement()
    {
        $type = DB::table('config')->where('key','advertisement_type')->value('value');
        if (empty($type)) {
            $info=array('info'=>'','status'=>2);
            return json_encode($info);
        }
        $advertisement =  DB::table('config')->where('key','popup_adv')->value('value');
        if (empty($advertisement)) {
            $info=array('info'=>'','status'=>2);
            return json_encode($info);
        }
        if ($type == 1) {
            $advertisement = json_decode($advertisement, true);
        }
        $data = [
            'type' => $type,
            'advertisement' => $advertisement
        ];
        $info=array('info'=>$data,'status'=>1);
        return json_encode($info);
    }

    /**
     * 我的参与
     */
    public function history(Request $request)
    {
        $input = $request->all();
        $status = isset($input['status'])? $input['status'] : 0;
        $member_id = DB::table('token')->where('token',$input['trd_session'])->value('member_id');

        $order = DB::table('order')
                  ->leftJoin('prize','order.prize_id','=','prize.id')
                    ->select('order.*')
                    ->where([
                        ['order.member_id','=',$member_id],
                        ['prize.status','=',$status]
                    ])
                  ->orderBy('order.order_id','desc')
                   ->get();
        $order = $order->toArray();
        foreach ($order as & $value) {
            $value->is_win = DB::table('prize_result')->where([
                ['prize_id',$value->prize_id],
                ['member_id',$member_id]
            ])->first();
            $value->pinfo = DB::table('prize')->where('id',$value->prize_id)->first();
            $value->pinfo->minfo = DB::table('member')->where('id',$value->pinfo->member_id)->first();
        }

        $info=array('info'=>$order,'status'=>1);
        return json_encode($info,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 我发起
     */
    public function launch(Request $request)
    {
        $input = $request->all();
        $status = isset($input['status'])? $input['status'] : 0;
        $member= DB::table('token')->where('token',$input['trd_session'])->first();

        $prize =DB::table('prize')
            ->where([
                ['member_id',$member->member_id],
                ['status',$status]
            ])
            ->orderBy('id','desc')
            ->get();
        $prize = $prize->toArray();
        foreach ($prize as &$value) {
            $value->minfo =$member;
        }
        $info=array('info'=>$prize,'status'=>1);
        return json_encode($info,JSON_UNESCAPED_UNICODE);
    }

    /*我的中奖*/
    public function mywin(Request $request)
    {
        $input = $request->all();
        $member_id= DB::table('token')->where('token',$input['trd_session'])->value('member_id');

        $order = DB::table('prize_result')
            ->leftJoin('prize','prize_result.prize_id','=','prize.id')
            ->select('prize_result.*')
            ->where('prize_result.member_id','=',$member_id)
            ->orderBy('prize_result.result_id','desc')
            ->get();
        $order = $order->toArray();

        foreach ($order as & $value) {
            $value->is_win = DB::table('prize_result')->where([
                ['prize_id',$value->prize_id],
                ['member_id',$member_id]
            ])->first();
            $value->pinfo = DB::table('prize')->where('id',$value->prize_id)->first();
            $value->pinfo->minfo = DB::table('member')->where('id',$value->pinfo->member_id)->first();
        }

        $info=array('info'=>$order,'status'=>1);
        return json_encode($info,JSON_UNESCAPED_UNICODE);
    }
    /*获取收货地址*/
    public function getaddress(Request $request)
    {
        $input = $request->all();
        $member_id= DB::table('token')->where('token',$input['trd_session'])->value('member_id');
        $data = DB::table('address')->where('member_id',$member_id)->get();
        if (empty($data)) {
            DB::table('address')->insert([
                ['member_id',$member_id],
                ['addtime',time()]
            ]);
            $data = [
                'name' => '',
                'phone' => '',
                'address' => ''
            ];
        }
        $info=array('info'=>$data,'status'=>1);
        return json_encode($info);
    }

    /*保存收货地址*/
    public function address(Request $request)
    {
        $input = $request->all();
        $member_id= DB::table('token')->where('token',$input['trd_session'])->value('member_id');
        $data = [
            'name' => $input['name'],
            'phone' => $input['phone'],
            'address' => $input['address'],
        ];
        DB::table('address')->where('member_id',$member_id)->update($data);
        $info=array('info'=>'ok','status'=>1);
        return json_encode($info);
    }
    /*获取配置*/
    public function config(Request $request)
    {
        $key = $request->input('key');
        if (empty($key)) {
            $info=array('info'=>'参数错误','status'=>2);
            return json_encode($info);
        }
        $config = DB::table('config')->where('key',$key)->value('value');
        if ($config) {
            $config = $config ;
        }
        elseif ($key == 'pay_function') {
            DB::table('config')->insert([
                ['key','pay_function'],
                ['value',5]
            ]);
            $config = 5;
        } elseif ($key == 'home_recommendation') {
            DB::table('config')->insert([
                ['key','home_recommendation'],
                ['value',1500]
            ]);
            $config = 1500;
        }

        $info=array('info'=>$config,'status'=>1);
        return json_encode($info);
    }
    /*发布权限*/
    public function release()
    {
        $is_release = $this->_release();
        $msg = '';
        if (!$is_release) {
            $msg = DB::table('config')->where('key','release_msg')->value('value');
            $msg = $msg ? $msg  : '无发布权限';
        }
        $data = [
            'is_release' => $is_release,
            'msg' => $msg
        ];
        $info=array('info'=>$data,'status'=>1);
        return json_encode($info);
    }

    private function _release()
    {
        $config = DB::table('config')->where('key','is_release')->first();
        $is_release = $config ? $config->value : 0;
        return $is_release;
    }

    /**
     * 店铺优惠券
     */
    public  function voucher(Request $request){
        $input = $request->all();
        $member_id= DB::table('token')->where('token',$input['trd_session'])->value('member_id');

        $goods = $this->is_voucher($member_id);
        if ($goods) {
            $info=array('info'=>$goods,'status'=>1);
            return json_encode($info);
        }
        $info=array('info'=>'','status'=>2);
        return json_encode($info);

    }


    public function  is_voucher($member_id)
    {
        $member = DB::table('member')->where('id',$member_id)->first();
        if ($member->shop_id < 1) {
            return false;
        }

        $shop = DB::table('shop')->where([['id',$member->shop_id],['is_del',0]])->first();

        if (empty($shop)) {
            return false;
        }
        $goods = DB::table('goods')->where('shop_id',$member->shop_id)->get();
        if (empty($goods)) {
            return false;
        }
        $goods = $goods->toArray();
        foreach ($goods as $k => $value) {

            $not_used = DB::table('voucher')->where([['goods_id',$value->id],['status',0]])->count();
            if ($not_used < 1) {
                unset($goods[$k]);
                continue;
            }
            $goods[$k]->not_used = $not_used;
        }
        if (empty($goods)) {
            return false;
        }

        return $goods;
    }
    /*抽奖发起人*/
    public function author(Request $request)
    {
        $input = $request->all();
        $member_id= DB::table('token')->where('token',$input['trd_session'])->value('member_id');
        $member = DB::table('member')->where('id',$member_id)->first();
        $member =$member->toArray();
        if ($member['user_img'] || $member['nickname']) {
            $info=array('info'=>'','status'=>1);
            return json_encode($info);
        }

        $info=array('info'=>'','status'=>2);
        return json_encode($info);
    }

    /**
     * 添加
     */
    public function add(Request $request)
    {
        $input = $request->all();
        $member_id= DB::table('token')->where('token',$input['trd_session'])->value('member_id');
        $member = DB::table('member')->where('id',$member_id)->first();
        $member =$member->toArray();
        if ($this->_release() != 1) {
            $info=array('info'=>'无发布权限','status'=>0);
            return json_encode($info);
        }

        if (!$member['user_img'] && !$member['nickname']) {
            $info=array('info'=>'','status'=>-1);
            return json_encode($info);
        }

        $attach_id = $input['attach_id'];
        $title = $input['title'];
        $desc_type = $input['desc_type'];
        $description = $input['description'];
        $uname = $input['uname'];
        $wechat_no = $input['wechat_no'];
        $wechat_title = $input['wechat_title'];

        $fir_cname = $input['fir_cname'];
        $sec_cname = isset($input['sec_cname'])?$input['sec_cname']:'';
        $trd_cname = isset($input['trd_cname'])?$input['trd_cname']:'';

        $fir_ptype = $input['fir_ptype'];
        $is_share = $input['is_share'];
        $is_command = $input['is_command'];

        $is_voucher = $this->is_voucher($member_id);

        if ($fir_ptype == 2) {
            $fir_val = htmlspecialchars_decode($input['fir_cardmsg']);
            $fir_num = $is_voucher ? $input['fir_num'] : count(json_decode($fir_val, true));
        } else {
            $fir_val = $input['fir_val'];
            $fir_num = $input['fir_num']?$input['fir_num']:0;
        }

        $sec_ptype = $input['sec_ptype'];
        if ($sec_ptype == 2) {
            $sec_val = htmlspecialchars_decode($input['sec_cardmsg']);
            $sec_num = $is_voucher ? $input['sec_num'] :  count(json_decode($sec_val, true));
        } else {
            $sec_val = $input['sec_val'];
            $sec_num = $input['sec_num']?$input['sec_num']: 0;
        }

        $trd_ptype = $input['trd_ptype'];
        if ($trd_ptype == 2) {
            $trd_val = htmlspecialchars_decode($input['trd_cardmsg']);
            $trd_num = $is_voucher ? $input['trd_num'] :  count(json_decode($trd_val, true));
        } else {
            $trd_val = $input['trd_val'];
            $trd_num = $input['trd_num']?$input['trd_num']:0;
        }

        $max_group_num = 0;//$input('max_group_num', 0);
        $type = $input['type']?$input['type']: 'people';
        $types = [
            'people' => 2,
            'time' => 1,
            'manual' => 3
        ];
        $type = $types[$type];

        $typevalue = $input['typevalue'];

        if ($type == 1) {
            $typevalue = strtotime($typevalue);
            if ($typevalue <= time()) {
                $info=array('info'=>'开奖时间已过，请重新选择时间','status'=>0);
                return json_encode($info);
            }
        }
        else if ($type == 2) {
            $num = $fir_num + $sec_num + $trd_num;
            if ($num > $typevalue) {
                $info=array('info'=>'开奖人数小于奖品数','status'=>0);
                return json_encode($info);
            }
        }
        $money = 0;

        if ($fir_ptype == 1 || $trd_ptype == 1 || $sec_ptype == 1) {

            if ($fir_ptype == 1) {
                $money += ($fir_val * $fir_num);
            }
            if ($sec_ptype == 1) {
                $money += ($sec_val * $sec_num);
            }
            if ($trd_ptype == 1) {
                $money += ($trd_val * $trd_num);
            }

            $red_package_fee = DB::table('config')->where('key','red_package_fee')->value('value');
            if ($red_package_fee && $red_package_fee > 0) {
                $fee = ceil($money * $red_package_fee) / 100;
                $money += $fee;
            }

        }

        $isjump = $input['isjump'];
        if ($isjump == 1) {
            $pay_function = DB::table('config')->where('key','pay_function')->value('value');
            $pay_function = $pay_function ? $pay_function['value'] : 5;
            $money += $pay_function;
        }

        if ($money > 0) {
            sleep(2);
            if ($member['money'] < $money) {

                //构造订单数据
                $orderid = $this->unifiedOrder($member['id'], $money);
                $xcx = DB::table('config')->where('key','title')->value('value');
                $xcx = $xcx ? $xcx : '';

                $order = array(
                    'tid' => $orderid, //订单号
                    'fee' => floatval($money), //支付参数
                    'title' => $xcx . '的订单', //标题
                );
//                global $_W;
//                $_W['openid'] = $member['openid'];
//                $_W['member']['uid'] = $member['id'];
//                $paydata = $this->pay($order);
//                if (is_error($paydata)) {
//                    //$this->result($paydata['errno'], $paydata['message']);
//                    json($paydata['message'], 0);
//                }
//                json($paydata, 2);
            }
            $res = $this->change($member['id'], $money, 5);
            if ($res == false) {
                $info=array('info'=>'奖品发布失败','status'=>0);
                return json_encode($info);
            }
        }

        $data = [
            'brief_description' => $title,
            'member_id' => $member['id'],
            'uname' => $uname,
            'wechat_no' => $wechat_no,
            'wechat_title' => $wechat_title,
            'typevalue' => $typevalue,
            'max_group_num' => $max_group_num,
            'desc_type' => $desc_type,
            'desc_text' => $desc_type,
            'type' => $type,
            'attach_id' => $attach_id,
            'fir_ptype' => $fir_ptype,
            'fir_num' => $fir_num,
            'fir_val' => $fir_val,
            'sec_ptype' => $sec_ptype,
            'sec_num' => $sec_num,
            'sec_val' => $sec_val,
            'trd_ptype' => $trd_ptype,
            'trd_num' => $trd_num,
            'trd_val' => $trd_val,
            'description' => $description,
            'fir_cname' => $fir_cname,
            'sec_cname' => $sec_cname,
            'trd_cname' => $trd_cname,
            'created' => time(),
            'is_share' => $is_share,
            'is_command' => $is_command
        ];
        if ($is_command == 1) {
            $data['command'] = $input['command'];
            if (empty($data['command'])) {
                $info=array('info'=>'请输入口令','status'=>0);
                return json_encode($info);
            }
        }


            if ($data['fir_ptype'] == 2 && $is_voucher) {
                $data['fir_ptype'] = 3;
                $data['fir_cardid'] = $input['fir_cardid'];
                if (!is_numeric($data['fir_cardid'])) {
                    return json_encode('请选择优惠券',JSON_UNESCAPED_UNICODE);
                }
                $res = $this->deduction($member['shop_id'], $data['fir_cardid'], $fir_num);
                if (!$res) {
                    return json_encode($this->error,JSON_UNESCAPED_UNICODE);
                }
                $data['fir_val'] = json_encode($res);
            }

            if ($data['sec_ptype'] == 2 && $is_voucher) {
                $data['sec_ptype'] = 3;
                $data['sec_cardid'] = $input['sec_cardid'];
                if (!is_numeric($data['sec_cardid'])) {
                    return json_encode('请选择优惠券',JSON_UNESCAPED_UNICODE);
                }
                $res = $this->deduction($member['shop_id'], $data['sec_cardid'], $sec_num);
                if (!$res) {
                    return json_encode($this->error,JSON_UNESCAPED_UNICODE);
                }
                $data['sec_val'] = json_encode($res);
            }
            if ($data['trd_ptype'] == 2 && $is_voucher) {
                $data['trd_ptype'] = 3;
                $data['trd_cardid'] = $input('trd_cardid');
                if (!is_numeric(!$data['trd_cardid'])) {
                    return json_encode('请选择优惠券',JSON_UNESCAPED_UNICODE);
                }
                $res = $this->deduction($member['shop_id'], $data['trd_cardid'], $trd_num);
                if (!$res) {
                    return json_encode($this->error,JSON_UNESCAPED_UNICODE);
                }
                $data['trd_val'] = json_encode($res);
            }
            file_put_contents('./1.txt', var_export($data, true));

            if (!DB::table('prize')->insert($data)) {
                return json_encode('发布失败1',JSON_UNESCAPED_UNICODE);
            }
            $insert_id = DB::table('prize')->insert($data);
            if ($data['fir_ptype'] == 1) {
                $this->bag($member['id'], $insert_id, $data['fir_val'], $data['fir_num']);
            }
            if ($data['sec_ptype'] == 1) {
                $this->bag($member['id'], $insert_id, $data['sec_val'], $data['sec_num']);
            }
            if ($data['trd_ptype'] == 1) {
                $this->bag($member['id'], $insert_id, $data['trd_val'], $data['trd_num']);
            }

            if ($isjump == 1 && $input('copyorjump') == 2) {
                $data = [
                    'prize_id' => $insert_id,
                    'appid' => $input('appid'),
                    'path' => $input('path'),
                    'extraData' =>  $input('extraData'),
                    'app_name' =>  $input('appname')
                ];
               DB::table('jump_program')->insert($data);
            }
        $info=array('info'=>$insert_id,'status'=>1);
        return json_encode($info);
    }

    public function unifiedOrder($member_id, $money)
    {
        $trade_no = date("YmdHis", time()) . $member_id . mt_rand(1000, 9999);
        $pay = [
            'member_id' => $member_id,
            'trade_no' => $trade_no,
            'money' => $money,
            'crested' => time()
        ];

        if (DB::table('pay_order')->insert($pay)) {
            return $trade_no;
        }
        return false;
    }

    public $error = '';
    /**
     * 资金变动
     *
     * @param $member_id
     * @param $money
     * @param int $type
     * @return bool
     */
    public function change($member_id, $money, $type = 1)
    {
        if ($money <= 0) {
            return true;
        }

        $member = DB::table('member')->where('id',$member_id)->first();
        $member = $member->toArray();
        if (in_array($type, [1, 6, 7])) {
            $after_money = $member['money'] + $money;
        } else {

            if ($member['money'] < $money) {
                $this->error = '余额不足';
                return false;
            }

            $after_money = $member['money'] - $money;
        }

        $update = [ 'money' => $after_money];
        if (!DB::table('member')->where('id',$member_id)->update($update)) {

            $this->error = '余额变动失败';
            return false;
        }

        $money_log = [
            'member_id' => $member_id,
            'money' => $money,
            'type' => $type,
            'created' => time()
        ];
        if (DB::table('money_log')->insert($money_log)) {
            return true;
        }

        $this->error = '日志更新出错';
        return false;
    }

    public function deduction($shop_id, $goods_id, $num)
    {
        $goods = DB::table('goods')->where([['id',$goods_id],['shop_id',$shop_id]])->first();
        if (empty($goods)) {
            $this->error = '该优惠券不存在';
            return false;
        }
        $voucher = DB::table('voucher')->where([['goods_id',$goods_id],['status',0]])->limit($num)->get();
        $voucher = $voucher->toArray();
        if (count($voucher) < $num) {
            $this->error = $goods['goods_name'] . '数量不足';
            return false;
        }
        $vou = [];
        foreach ($voucher as $value) {
            $vou[] = $value->voucher;
            if (!DB::table('voucher')->where('id',$value->id)->update(['status'=>1])) {
                $this->error = '发起失败';
                return false;
            }
        }
        return $vou;
    }

    public function bag($member_id, $prize_id, $money, $number)
    {
        $sql = 'INSERT INTO ' . 'ims_cj_red_bag'. ' (member_id,prize_id,red_bag_money,created) VALUES';
        $t = time();
        $mess='';
        for ($i = 0; $i < $number; $i++) {
            $mess .= "({$member_id}, {$prize_id}, {$money}, {$t}),";
        }


        if (!DB::insert($sql)) {
            $this->error = '设置失败';
            return false;
        }

        return true;



        $red = $this->getRedPackage($money, $number);

        if (empty($red)) {
            $this->error = '每个红包金额最少为0.01元';
            return false;
        }
        $sql = 'INSERT INTO ' .'ims_cj_red_bag' . ' (member_id,prize_id,red_bag_money,created) VALUES';
        $t = time();
        foreach ($red as $v) {
            $sql .= "({$member_id}, {$prize_id}, {$v}, {$t}),";
        }
        $sql = rtrim($sql, ',');
        if (!DB::insert($sql)) {
            $this->error = '设置失败';
            return false;
        }

        return true;
    }


    public function getRedPackage($money, $num, $min = 0.01)
    {
        //将最大金额  设为红包总数
        $max = $money;
        $data = array();
        //最小金额*数量  不能大于  总金额
        if ($min * $num > $money) {
            return $data;
        }

        //最大金额*数量  不能大于  总金额
        if ($max * $num < $money) {
            return $data;
        }
        //如果红包数量为1  直接返回总数
        if ($num == 1){
            $data[] = $money;
            return $data;
        }
        while ($num >= 1) {
            $num--;
            $kmin = max($min, $money - $num * $max);
            $kmax = min($max, $money - $num * $min);
            $kAvg = $money / ($num + 1);
            //获取最大值和最小值的距离之间的最小值
            $kDis = min($kAvg - $kmin, $kmax - $kAvg);

            //获取0到1之间的随机数与距离最小值相乘得出浮动区间，这使得浮动区间不会超出范围
            $r = ((float)(rand(1, 10000) / 10000) - 0.5) * $kDis * 2;
            $k = round($kAvg + $r, 2);
            $money -= $k;
            $data[] = sprintf("%.2f",$k);
        }
        return $data;
    }
    /*注册*/
    public function register(Request $request)
    {
        $input = $request->all();
        $member_id= DB::table('token')->where('token',$input['trd_session'])->value('member_id');

        if (!$input['nickname'] || !$input['headimgurl']) {
            $info=array('info'=>'非法请求','status'=>0);
            return json_encode($info);
        }

        $update = [
            'nickname' => $input['nickname'],
            'user_img' => $input['headimgurl'],
            'gender' =>$input['gender'],
            'province' => $input['province'],
            'city' => $input['city'],
            'country' => $input['country'],
            'add_time' => time(),
            'set_time' => time()
        ];
        DB::table('member')->where('id',$member_id)->update($update);
        $info=array('info'=>'ok','status'=>1);
        return json_encode($info);
    }


}

